package com.eryos.test.springsecurity.server.security;

/**
 * Project :  SpringSecuritySimple
 * Author :   Olivier Combe
 * URL :      http://eryos-tech.blogspot.com/
 *
 * Copyright (C) 2011 - Olivier Combe 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */

import java.util.ArrayList;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.eryos.test.springsecurity.shared.SimpleUser;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class SimpleUserDetailService implements UserDetailsService {

	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		
		Key key = KeyFactory.createKey(SimpleUser.USER_TYPE, username);
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); 
		
		try { 
			/* Trying to retrieve the used */
			Entity user = datastore.get(key); 

			/* User is found */
			ArrayList<GrantedAuthority> authRoles = new ArrayList<GrantedAuthority>();
			for ( String role : (ArrayList<String>)user.getProperty(SimpleUser.USER_AUTHORITIES) )
				authRoles.add(new GrantedAuthorityImpl(role));

			/* Define a Spring User */
			User usr = new User( 
					(String)user.getProperty(SimpleUser.USER_USERNAME), 
					(String)user.getProperty(SimpleUser.USER_ENCODED_PASS), 
					(Boolean)user.getProperty(SimpleUser.USER_ENABLED), 
					true, 
					true, 
					true, 
					authRoles);

			return usr; 

		} catch (EntityNotFoundException e) { 
			System.out.println("[SimpleUserDetailsService] : User not found : "+username);
			return null;
		}
	}
}
